const { Sequelize, DataTypes } = require("sequelize");

// 连接到 MySQL 数据库
const sequelize = new Sequelize("my_db_02", "root", "", {
  host: "127.0.0.1",
  dialect: "mysql",
});

// 定义群组模型
const Group = sequelize.define("Group", {
  name: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
  },
  users: {
    type: DataTypes.JSON,
    defaultValue: [],
  },
  messages: {
    type: DataTypes.JSON,
    defaultValue: [],
  },
});

// 同步模型到数据库中
sequelize
  .sync()
  .then(() => {
    console.log("数据库同步完成");
  })
  .catch((err) => {
    console.error("数据库同步失败:", err);
  });

async function createGroup(groupName) {
  await Group.create({ name: groupName, users: [], messages: [] });
}

async function joinGroup(groupName, username) {
  const group = await Group.findOne({ where: { name: groupName } });
  if (group) {
    const users = group.users || [];
    if (!users.includes(username)) {
      users.push(username);
      await group.update({ users });
    }
  }
}

async function sendMessage(message) {
  const group = await Group.findOne({ where: { name: message.group } });
  if (group) {
    const messages = group.messages || [];
    messages.push({ user: message.user, text: message.text });
    await group.update({ messages });
  }
}

module.exports = { createGroup, joinGroup, sendMessage };
